package com.ciwong.epaper.modules.wordlist;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.os.Build;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.style.UnderlineSpan;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.TextView;

import com.ciwong.ciwongwrite.utils.CWUtils;
import com.ciwong.epaper.R;
import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.modules.evaluate.bean.AnswerRecorder;
import com.ciwong.epaper.modules.evaluate.ui.BaseSpeechActivity;
import com.ciwong.epaper.modules.evaluate.util.SpeechController;
import com.ciwong.epaper.modules.evaluate.util.SpeechUtils;
import com.ciwong.epaper.modules.me.ui.JsonParserUtil;
import com.ciwong.epaper.modules.me.util.MeJumpManager;
import com.ciwong.epaper.modules.wordlist.bean.PageListBean;
import com.ciwong.epaper.modules.wordlist.bean.WordAnswerList;
import com.ciwong.epaper.modules.wordlist.bean.WordDownloadInfo;
import com.ciwong.epaper.modules.wordlist.util.WordBookDownload;
import com.ciwong.epaper.modules.wordlist.util.WordOnPlayListener;
import com.ciwong.epaper.util.ALiYunManager;
import com.ciwong.epaper.util.EConstants;
import com.ciwong.epaper.util.ESystem;
import com.ciwong.epaper.util.RequestCode;
import com.ciwong.epaper.util.ScoreUtils;
import com.ciwong.epaper.widget.evaluate.UnitSpeechView;
import com.ciwong.libs.audio.play.AudioPlayer;
import com.ciwong.libs.audio.play.OnPlayListener;
import com.ciwong.libs.oralevaluate.bean.EvaluateResult;
import com.ciwong.libs.oralevaluate.bean.Word;
import com.ciwong.libs.utils.CWSys;
import com.ciwong.libs.utils.NetworkUtils;
import com.ciwong.libs.utils.StringUtils;
import com.ciwong.mobilelib.bean.UserInfoBase;
import com.ciwong.mobilelib.i.ViewOnClickListener;
import com.ciwong.mobilelib.ui.BaseActivity;
import com.ciwong.mobilelib.utils.BaseConstants;
import com.ciwong.mobilelib.utils.ToastUtil;
import com.ciwong.mobilelib.widget.BuyServiceDialog;
import com.unisound.edu.oraleval.sdk.sep15.IOralEvalSDK;
import com.unisound.edu.oraleval.sdk.sep15.SDKError;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import static com.ciwong.epaper.util.ALiYunManager.ACCESS_URL;

/**
 * Created by young  on 2018/3/27.
 */

public class WordListReadControler extends BaseWordListReadController implements
        UnitSpeechView.OnPageSelectChangeListener, AdapterView.OnItemClickListener {

    private WordSpeechView speechView;
    private List<PageListBean> unitWords;

    private TextView scoreView, seeScoreView;

    private String unitText;

    private long startTime;


    private ListAdapter adapter;
    /**
     * 默认服务包剩余使用时间
     */
    public boolean serviceExpired;

    private BaseWordListReadController.OnSpeechListener mOnUnitSpeechListener;


    private OnPlayListener listener = new OnPlayListener() {
        @Override
        public void stop(Object mp3) {
            if (isPause()) {
                return;
            }
            //这个地方要修改  不要按TAG判断   开始录音
            if (ASIDE_AUDIO_TAG.equals(mp3)) {
                record();
                return;
            }

        }

        @Override
        public void onPlayStart(Object mp3) {

        }

        @Override
        public void onReadPlayer(long duration, Object mp3) {

        }

        @Override
        public void onError(int errorCode, final Object tag) {

        }

        @Override
        public void onBuffer(Object mp3, long progress, long total) {

        }

        @Override
        public void onPlaying(long arg0, long arg1) {

        }

    };

    /**
     * 构造函数
     *
     * @param mContext 上下文
     */
    protected WordListReadControler(BaseActivity mContext) {
        super(mContext);
        this.mContext = mContext;
    }

    /**
     * 构造函数
     *
     * @param wordSpeechView {@link UnitSpeechView}
     */
    public WordListReadControler(BaseActivity mContext, WordSpeechView wordSpeechView, boolean serviceExpired) {
        super(mContext);
        this.mContext = mContext;
        speechView = wordSpeechView;
        this.serviceExpired = serviceExpired;
        init();
    }

    private void init() {
        speechView.setOnPageSelectChangeListener(this);
        initYZSEngine();
        //设置评分系数
        ScoreUtils.setSocreCoefficient();
    }

    /**
     * 设置语音评测监听事件
     *
     * @param listener {@link SpeechController.OnSpeechListener}
     */
    public void setOnUnitSpeechListener(BaseWordListReadController.OnSpeechListener listener) {
        this.mOnUnitSpeechListener = listener;
    }


    private File getSoundPath(PageListBean word, int index) {
        return new File(ESystem.getWordListRecordPath(),
                StringUtils.md5("record" + word.getContent()) + EConstants.AUDIO_DEFAULT_SUFFIX);
    }
    //

    /**
     * 设置单元单词
     *
     * @param words List<UnitWord>
     */
    public void setUnitWord(List<PageListBean> words, WordListBottomView wordBottomView,
                            TextView scoreView, TextView seeScoreView, long userId) {

        unitWords = words;
        this.scoreView = scoreView;
        this.seeScoreView = seeScoreView;

        answerCount = words == null ? 0 : words.size();
        if (speechView != null) {
            speechView.setData(words, wordBottomView, scoreView, userId,
                    currentListenAndRepeatIndex);
        }
        if (unitWords == null || unitWords.isEmpty()) {
            return;
        }
        if (unitText == null || "".equals(unitText)) {
            unitText = StringUtils.md5(words.get(0).getContent() + "");
        }
        int len = words.size();

    }

    /**
     * 设置单元单词标题
     */
    public void setUnitText(String text) {
        unitText = text;
    }

    /**
     * 开始录音提示音
     *
     * @param index 下标
     */
    private void startRecordHint(final int index) {
        if (index >= unitWords.size()) {
            return;
        }
        if (isPause()) {
            return;
        }
        AudioPlayer.getInstance().setOnPlayListener(listener).play(R.raw.repeat_read_start_record, mContext,
                ASIDE_AUDIO_TAG);
        speechView.playHintState();
    }

    /**
     * 录音
     */
    private void record() {
        if (isPause()) {
            return;
        }
        try {
            operateStatus = OPERATE_STATUS_RECORD;

            //显示录音图标//开始录音动画
            speechView.startRecord();
            //自动更新进度
            speechView.autoUpdateProgress((int) audioDuration);
            //正常的录音状态，即第一次的录音
            PageListBean word = unitWords.get(currentListenAndRepeatIndex);
            PageListBean.ResourceBean resource = word.getResource();
            if (resource != null) {
                if (resource.getSyllable() != null && !"".equals(resource.getSyllable().trim())) {
                    eEngine.setText(resource.getSyllable());
                } else {
                    eEngine.setText(word.getContent());
                }
            } else {
                //启动
                eEngine.setText(word.getContent());
            }
            //音频文件地址
            eEngine.setRecordPath(getSoundPath(word, currentListenAndRepeatIndex).getAbsolutePath());
            UserInfoBase userInfoBase = EApplication.getInstance().getUserInfoBase();
            if (null != userInfoBase) {
                eEngine.setUid(String.valueOf(userInfoBase.getUserId()));
            }

            eEngine.start("E");

            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (isPause()) {
                        eEngine.stop();
                        return;
                    }
                    stopRecord();
                }
            }, audioDuration);


        } catch (NullPointerException e) {
            e.getStackTrace();
        } catch (OutOfMemoryError error) {
            error.getStackTrace();
        }

    }

    /**
     * 停止录音
     */
    private void stopRecord() {
        eEngine.stop();
        //如果是已经暂停了 则不再执行
        if (operateStatus == STATUS_STOP) {
            return;
        }
        speechView.playHintState();
    }


    //开始学习
    public void startStudy() {
        try {
            //切换播放按钮状态
            speechView.showAndgoneNextBtn(false, false);
            operateStatus = STATUS_NORMAL;
            //切换单词显示页面
            speechView.animTo(currentListenAndRepeatIndex);
            //先添加纪录
            //答案记录
            if (answerRecorders == null) {
                answerRecorders = new ArrayList<WordAnswerList>();
            }


            //设置分数和题号
            onCompleteCount(0);
            //播放音频
            if (NetworkUtils.isOnline()) {
                playWords();
            } else {
                ToastUtil.INSTANCE.toastCenterNoNetError();
                speechView.showAndgoneNextBtn(true, false);
            }


        } catch (Exception e) {
            e.getStackTrace();
        }
    }

    //播放单词原音
    public void playWords() {
        synchronized (unitWords)//播放原音
        {
            operateStatus = OPERATE_STATUS_PLAYING;
            if (currentListenAndRepeatIndex >= unitWords.size()) {
                return;
            }
            final PageListBean unitWord = unitWords.get(currentListenAndRepeatIndex);
            WordDownloadInfo wordDownloadInfo = new WordDownloadInfo();
            wordDownloadInfo.setNativeAudio(true);
            wordDownloadInfo.setAudioUrl(unitWord.getResource().getAudioUrl());
            wordDownloadInfo.setWord(unitWord.getContent());
            WordBookDownload.getInstance().startPlay(wordDownloadInfo, new WordOnPlayListener() {
                @Override
                public void onDownloading(WordDownloadInfo wordDownloadInfo) {
                    speechView.setWordLoading(true);
                }

                @Override
                public void onDownloadCompelted(WordDownloadInfo wordDownloadInfo) {
                    speechView.setWordLoading(false);
                }

                @Override
                public void onDownloadFailed(WordDownloadInfo wordDownloadInfo, Throwable e) {
                    speechView.setWordLoading(false);
                    startRecordHint(currentListenAndRepeatIndex);
                }

                @Override
                public void onReadPlayer(long l, Object o) {
                    // 获取播放单词时长
                    if (!"pcm".equals(o + "")) {
                        //显示播放单词原音状态
                        speechView.play();//在这里显示是为了错误的时候 还没有显示播放图标
                        audioDuration = RECORD_ADD_DURATION;
                    }
                }

                @Override
                public void onPlayStart(Object o) {

                }

                @Override
                public void stop(Object o) {
                    //原音播放完成之后需要播放提示音
                    startRecordHint(currentListenAndRepeatIndex);
                }

                @Override
                public void onError(int i, Object o) {
                    startRecordHint(currentListenAndRepeatIndex);
                }

                @Override
                public void onBuffer(Object o, long l, long l1) {

                }

                @Override
                public void onPlaying(long l, long l1) {
                    int progress = (int) l1;
                    int max = (int) l;
                    mOnUnitSpeechListener.updateProgress(max, progress);//更新播放进度
                    // .setRoundProgressAndMax()
                }
            });

        }

    }


    private void onOneWordComplete(int index, int score, EvaluateResult evaluateResult, String url) {
        try {
            if (unitWords == null) {
                return;
            }
            if (currentListenAndRepeatIndex >= answerRecorders.size()) {
                WordAnswerList wordAnswerList = new WordAnswerList();
                wordAnswerList.setWordId(unitWords.get(currentListenAndRepeatIndex).getWordId());
                answerRecorders.add(wordAnswerList);
            }
            ALiYunManager.getInstance().addMP3(getLocPath(unitWords.get(currentListenAndRepeatIndex)).getAbsolutePath(),
                    getLocPath(unitWords.get(currentListenAndRepeatIndex)), System.currentTimeMillis());
            Iterator wordAnswerListIterator = answerRecorders.iterator();
            while (wordAnswerListIterator.hasNext()) {
                WordAnswerList wordAnswerList = (WordAnswerList) wordAnswerListIterator.next();
                if (wordAnswerList.getWordId().equals(unitWords.get(currentListenAndRepeatIndex).getWordId())) {
                    wordAnswerList.setScore(score);
                    wordAnswerList.setYzsAudioUrl(url);
                    wordAnswerList.setAudioUrl(getNetUrl(unitWords.get(currentListenAndRepeatIndex)));
                    if (EApplication.isSymbolColoration) {
                        String evaluateResultString = JsonParserUtil.toJson(evaluateResult);
                        if (!TextUtils.isEmpty(evaluateResultString)) {
                            wordAnswerList.setResult(evaluateResultString);
                        }
                    }


                }
            }

        } catch (Exception e) {
            e.getStackTrace();
        }

    }

    public File getLocPath(PageListBean pageListBean) {

        return new File(ESystem.getWordListRecordPath(),
                StringUtils.md5("record" + pageListBean.getContent())
                        + EConstants.AUDIO_DEFAULT_SUFFIX);
    }

    public String getNetUrl(PageListBean PageListBean) {
        return ACCESS_URL + "work/followread/" + CWUtils.getReadTime(System.currentTimeMillis()) + "/" + CWSys
                .getSharedLong(BaseConstants.SHARE_PRE_CURR_LOGIN_USER, 0) + "/"
                + StringUtils.md5("record" + PageListBean.getContent())
                + EConstants.AUDIO_DEFAULT_SUFFIX;
    }


    private void onCompleteCount(final float score) {
        if (mOnUnitSpeechListener != null) {
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    mOnUnitSpeechListener.onComplete(score);
                }
            });
        }
    }


    /**
     * 暂停
     */
    public void pause() {
        try {
            if (operateStatus < 0) {
                return;
            }
            operateStatus = -operateStatus;
            if (operateStatus == OPERATE_STATUS_PLAY_PAUSE) {
                AudioPlayer.getInstance().stop();
            } else if (operateStatus == OPERATE_STATUS_RECORD_PAUSE) {
                eEngine.cancel();
            }
            speechView.setCanScroll(false);//设置是否可以滑动  不可以滑动
            speechView.resetInitState();
            if (currentListenAndRepeatIndex == unitWords.size() - 1) {
                speechView.showAndgoneNextBtn(true, true);
            } else {
                speechView.showAndgoneNextBtn(true, false);
            }
        } catch (Exception e) {
            e.getStackTrace();
        }


    }

    /**
     * 停止跟读
     */
    public void stop() {
        ////停止状态
        operateStatus = STATUS_STOP;
        AudioPlayer.getInstance().stop();
        speechView.resetInitState();
        if (eEngine != null) {
            eEngine.stop();
        }
        mHandler.removeCallbacksAndMessages(this);
    }

    /**
     * 释放资源
     */
    public void release() {

    }

    @Override
    public void onError(IOralEvalSDK iOralEvalSDK, SDKError sdkError, IOralEvalSDK.OfflineSDKError offlineSDKError) {
        pause();//暂停状态
        if (mOnUnitSpeechListener != null) {
            mOnUnitSpeechListener.recError(iOralEvalSDK, sdkError, offlineSDKError);
        }
    }

    @Override
    public void onStart() {
        // BaseApplication.log = YZSEngine.sb;
    }

    private boolean isSoundToLow = true;

    @Override
    public void onVolume(int rms) {
        if (rms > 40) {
            isSoundToLow = false;
        }
    }

    @Override
    public void onStop(final int i, final EvaluateResult eResult, final String url) {
        if (i == -3) {//没有权限的时候  应该暂停
            //speechView.resetInitState();//如果暂停  则要暂停按钮状态改变
            pause();//暂停状态
            return;
        }
        //无评测结果
        if (eResult == null) {
            onError(null, new SDKError(SDKError.Category.Server, -9999, null), null);
            return;
        }
        // BaseApplication.log = YZSEngine.sb;
        eResult.setScore(/* ar.getScore() */SpeechUtils
                .scoreOptimize(eResult.getScore()));
        mHandler.post(new Runnable() {

            @Override
            public void run() {
                if (i == -2) {// 评测库返回错误
                    speechView.playHintState();
                }
                int score = (int) eResult.getScore();
                onEvaluated(score, isPlayAssess);
                if (serviceExpired) {
                    speechView.showResult(eResult);
                    //音标染色
                    if (EApplication.isSymbolColoration) {
                        speechView.setSymbolColoration(eResult);
                    }
                }

                //添加答案并保存答案
                onOneWordComplete(currentListenAndRepeatIndex, score, eResult, url);
                //如果当前播放的下标还在句子列表中就继续播放下一个句子

                showResultScore(eResult.getScore());//显示分数

                if (unitWords != null && currentListenAndRepeatIndex < unitWords.size() - 1) {
                    speechView.showAndgoneNextBtn(true, false);
                } else {
                    speechView.showAndgoneNextBtn(true, true);
                }
                if ((readCount <= 3 && score < 80 && isSoundToLow)) {
                    ToastUtil.INSTANCE.toastCenter(mContext, R.string.read_sound_too_low_tips, R.mipmap.ic_increase_volume);

                }


                isSoundToLow = true;

            }
        });
        // BaseApplication.log = YZSEngine.sb;
    }


    public static int readCount = 0;
    //录音结束后回调


    @Override
    public void onStartOralEval() {
        readCount++;
    }

    private AnswerRecorder onEvaluated(int score, boolean playResult) {
        if (currentListenAndRepeatIndex >= unitWords.size()) {
            return null;
        }
        PageListBean word = unitWords.get(currentListenAndRepeatIndex);
        return onEvaluated(score, getSoundPath(word, currentListenAndRepeatIndex).getAbsolutePath(),
                playResult);
    }

    @Override
    public void randomShow() {
        PageListBean word = unitWords.get(currentListenAndRepeatIndex);
        String[] arr = SpeechUtils.replaceAsSpace(word.getContent()).split("");
        List<Word> gradeWords = new ArrayList<Word>();
        for (String s : arr) {
            Word w = new Word();
            w.setText(s);
            int random = (int) (Math.random() * 10 / 2);
            w.setScore(random);
            gradeWords.add(w);
        }
        final float score = (int) (Math.random() * 10 / 2);
        EvaluateResult eResult = new EvaluateResult();
        eResult.setScore(score);
        eResult.setWords(gradeWords);
        AnswerRecorder ar = onEvaluated((int) score, true);
        if (ar != null) {
            eResult.setScore(ar.getScore());
        }
        speechView.showResult(eResult);
    }

    @Override
    public void onPageSelected(int index) {
        currentListenAndRepeatIndex = index;
    }


    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
                            long id) {


    }


    //显示评测结果
    public void showResultScore(float score) {
        try {
            if (serviceExpired) {
                int bg;
                int scoreColor;
                if (score < SpeechUtils.SCORE_2) {
                    scoreColor = R.color.score_red;
                    bg = R.mipmap.score_red_rep;
                } else if (score < SpeechUtils.SCORE_4) {
                    scoreColor = R.color.score_yellow;
                    bg = R.mipmap.score_orange_rep;
                } else {
                    scoreColor = R.color.score_green_word;
                    bg = R.mipmap.score_green_rep;
                }
                if (scoreView != null) {
                    Drawable drawable = mContext.getResources().getDrawable(bg);
                    drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                    scoreView.setCompoundDrawables(null, null, null, drawable);
                    // scoreView.setBackgroundResource(bg);
                    int changeSocre = (int) score;
                    scoreView.setText(changeSocre + "分");
                    scoreView.setTextColor(mContext.getResources().getColor(scoreColor));
                    scoreView.setVisibility(View.VISIBLE);
                    seeScoreView.setVisibility(View.GONE);
                }
            } else {
                scoreView.setText("已提交");
                scoreView.setTextColor(mContext.getResources().getColor(R.color.color_light_green));
                scoreView.setTextSize(18);
                scoreView.setVisibility(View.VISIBLE);

                String text = "查看分数";
                SpannableString spannableString = new SpannableString(text);
                spannableString.setSpan(new UnderlineSpan(), 0, text.length(), 0);
                seeScoreView.setText(spannableString);
                seeScoreView.setOnClickListener(new ViewOnClickListener() {
                    @Override
                    public void avertRepeatOnClick(View v) {
                        setBuyServiceDialog();
                    }
                });
                seeScoreView.setVisibility(View.VISIBLE);
            }
        } catch (Exception e) {
            e.getStackTrace();
        }

    }

    private BuyServiceDialog buyServiceDialog;

    public void setBuyServiceDialog() {
        if (buyServiceDialog == null) {
            buyServiceDialog = new BuyServiceDialog(mContext);
            buyServiceDialog.setMenuOnClickListeners(new ViewOnClickListener() {
                @Override
                public void avertRepeatOnClick(View v) {
                    //拓展服务
                    MeJumpManager.jumpToResourseCenterH5Activity(mContext, R.string.go_back, mContext.getResources().getString(R.string.resource_center));
                    buyServiceDialog.dismiss();
                }
            });
            buyServiceDialog.setClosOnClickListeners(new ViewOnClickListener() {
                @Override
                public void avertRepeatOnClick(View v) {
                    buyServiceDialog.dismiss();
                }
            });
        }
        buyServiceDialog.show();
    }

    public void scoreViewGone() {
        seeScoreView.setVisibility(View.VISIBLE);
        scoreView.setVisibility(View.GONE);
    }

    /**
     * 获取上传MP3 文件KEY
     *
     * @param uploadFilePath 上传文件路径
     * @return KEY
     */
    private String getMP3Key(String uploadFilePath) {
        return "work/followread/" + CWSys
                .getSharedLong(BaseConstants.SHARE_PRE_CURR_LOGIN_USER, 0) + "/"
                + new File(uploadFilePath).getName();
    }

}
